﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using ShopOnline;
using System.IO;

public partial class Controls_Header : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        liControlPanel.Visible = View_Users.GetCurrentUser() != null;
        ScriptManager.RegisterStartupScript(this, this.GetType(), ClientID, "initHeader();", true);
        if(!IsPostBack)
            RefreshState();
    }

    protected void lnkLossPassword_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtUserName.Text == "")
            {
                ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showErrorAlert('All For You Online', 'Please provide your registered email address.', 8000);", 1), true);
                return;
            }

            Customers cust = Customers.GetCustomerByEmail(txtUserName.Text);
            if (cust.RowCount <= 0)
            {
                ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showErrorAlert('All For You Online', 'Invalid Email Address.', 8000);", 1), true);
                return;
            }

            Guid guid = Guid.NewGuid();
            string newPass = guid.ToString().Replace("-", "").Substring(0, 10);

            string tempFile = Server.MapPath("~/MailTemplates/PasswordRecovery.htm");
            string content = File.ReadAllText(tempFile);
            content = string.Format(content, newPass, cust.s_CustomerName, Branches.CurrentBranch.s_Phone);

            cust.Password = POSSystem.BLL.Utilities.CreateMD5Hash(newPass);
            cust.Save();

            POSSystem.BLL.Utilities.SendEmail(txtUserName.Text, "Password Recovery", content);
            ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showNotification('All For You Online', 'New password has been sent to your email!', 8000);", 1), true);
        }
        catch (Exception ex)
        {
            ErrorLog.WriteToFile("Password Recovery", ex.Message, ex.StackTrace );
        }
    }

    public void lnkLogout_OnClick(object sender, EventArgs e)
    {
        View_Customers.SetCurrentUser(null);
        RefreshState();
        Response.Redirect(Request.Url.PathAndQuery);
    }

    public void btnLogin_Click(object sender, EventArgs e)
    {
        try
        {
            View_Customers cust = View_Customers.GetCustomerByEmail(txtUserName.Text);
            if (cust.RowCount <= 0)
            {
                ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showErrorAlert('All For You Online', 'Invalid email address.', 8000);", 1), true);
                return;
            }

            string password = POSSystem.BLL.Utilities.CreateMD5Hash(txtPassword.Text);
            if (cust.IsColumnNull(View_Customers.ColumnNames.Password) || cust.Password != password)
            {
                ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showErrorAlert('All For You Online', 'Invalid password.', 8000);", 1), true);
                return;
            }

            View_Customers.SetCurrentUser(cust);

            //refresh selected items price
            string ids = "";
            BasePage.SelectedItems.Rewind();
            BasePage.SelectedItems.Filter = "";
            for (int i = 0; i < BasePage.SelectedItems.RowCount; i++)
            {
                ids = BasePage.SelectedItems.s_ProductID + ",";
                BasePage.SelectedItems.MoveNext();
            }

            if (ids.EndsWith(","))
                ids = ids.Remove(ids.Length - 1);

            Products p = Products.GetProductsByIds(ids);

            BasePage.SelectedItems.Rewind();
            for (int i = 0; i < Cart.SelectedItems.RowCount; i++)
            {
                p.Filter = Products.ColumnNames.ID + "=" + Cart.SelectedItems.s_ProductID;
                if (p.RowCount > 0)
                {
                    if (cust != null && cust.Price == CustomerType.CustomerPrice.DealerPrice)
                        BasePage.SelectedItems.s_CustomerPrice = p.s_DealerPrice;
                    else if (cust != null && cust.Price == CustomerType.CustomerPrice.PartnerPrice)
                        BasePage.SelectedItems.s_CustomerPrice = p.s_PartnerPrice;
                    else
                        BasePage.SelectedItems.s_CustomerPrice = p.s_SalePrice;
                }
                Cart.SelectedItems.MoveNext();
            }

            RefreshState();
            Response.Redirect(Request.Url.PathAndQuery);
        }
        catch (Exception ex)
        {
            ErrorLog.WriteToFile("LoginCtrl.ascx.cs", "btnLogin_Click", ex.StackTrace);
            throw ex;
        }
    }

    private void RefreshState()
    {
        dlvLogout.Visible = View_Customers.GetCurrentUser() != null;
        divLogin.Visible = View_Customers.GetCurrentUser() == null;
        if (View_Customers.GetCurrentUser() != null)
            lblCustomerName.Text = View_Customers.GetCurrentUser().s_CustomerName;
    }
}